#include "httpdownload.h"
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QEventLoop>
#include "HttpManage.h"
HttpDownload::HttpDownload(const QUrl& url, const QString localPath)
    :m_url(url)
    ,m_localPath(localPath)
{}

void HttpDownload::run()
{
    QEventLoop eventLoop;

    QFile file(m_localPath);
    if(!file.open(QFile::OpenModeFlag::WriteOnly))
    {
        qDebug()<<"文件打开失败";
        return ;
    }
    QNetworkAccessManager manager;
    QNetworkRequest request(m_url);
    // 添加 Bearer Token（如果存在）
    QString token = HttpManage::GetInstance()->getToken();
    QString uid = HttpManage::GetInstance()->getUid();
    if (!token.isEmpty())
    {
        request.setRawHeader("Authorization", "Bearer " + token.toUtf8());
    }
    if(!uid.isEmpty())
    {
        request.setRawHeader("X-User-UID", uid.toUtf8());
    }
    QNetworkReply* reply = manager.get(request);

    connect(reply,&QNetworkReply::downloadProgress,this,&HttpDownload::downloadProgress);

    connect(reply,&QNetworkReply::downloadProgress,[&](qint64 bytesReceived,qint64 bytesTotal){
        qDebug() << bytesReceived << bytesTotal;
        file.write(reply->readAll());
    });

    connect(reply,&QNetworkReply::finished,this,&HttpDownload::finished);

    connect(reply,&QNetworkReply::finished,[&](){
        qDebug() << "下载完成";
        reply->deleteLater();
        file.close();
        eventLoop.quit();
    });
    eventLoop.exec();
}
